<template>
  <div
    class="page__register"
  >
    <span
      class="back op-7 link-btn inherit"
      @click="handleClose()"
    >
      <svg-icon
        icon-class="arrow"
        class=""
      />
      返回
    </span>
    <h2>注册</h2>
    <form-list
      ref="refForm"
      :strong-password="true"
      :label="['phone', 'code', 'pwd', 'confirmPwd', 'protocol']"
    />
    <div class="actions">
      <el-button
        class="main-btn"
        type="primary"
        size="large"
        @click="handleRegister"
      >
        注册
      </el-button>
      <p class="fs12 mt10 text-center">
        <span class="op-7">我有账号？</span>
        <span
          class="link-btn inherit"
          @click="handleClose()"
        >立即登录</span>
      </p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import formList, { type API } from "@/components/phone-form/form.vue";
import PsMessage from "@/components/message/index";
import { systemAppStore } from "@/stores/system";
import { userAppStore } from "@/stores/user";
import { checkUserIsExist, register } from "@/api/login";
import { getPwdMD5Str } from "@/utils";
import useMixins from "./mixins";
const { onLoginFinish } = useMixins();
const _userAppStore_ = userAppStore();
const system = systemAppStore();

const refForm = ref<API>();
const handleClose = (type="phoneLogin") => {
  PsMessage.closeAll();
  const data: any = {}
  if(type){
    data.type = type
    data.query = {
      loginType: "pwd"
    }
  }
  _userAppStore_.setACDialogType(data);
};
const handleRegister = async () => {
  const form = await refForm.value?.validate();
  if (!form) return;
  const res = await handlePhoneRegister(form, system.appInfo);
  if (res) handleClose("");
};

async function handlePhoneRegister(
  form: any,
  system: any
): Promise<boolean> {
  const userData = await checkUserIsExist(form.phone);
  if (userData?.data?.existed) {
    PsMessage("该手机号已注册");
    return false;
  }

  const params = {
    type: "phone",
    phoneNumber: form.phone,
    pwd: getPwdMD5Str(form.pwd),
    code: form.code,
    codeID: form.phone,
    channel: system.channel,
    uuid: system.uuid,
    device_name: system.device_name,
    version: system.version,
  };

  const res = await register(params);
  PsMessage("账号注册成功");
  const data = res.data || {};
  data.isAutoLogin = true;
  data.loginType = "phoneLogin";
  onLoginFinish(data);
  return true
}
</script>

<style lang="scss" scoped>
.page__register {
  position: absolute;
  inset: 0;
  padding: 32px 23px 0 23px;
  background-color: $color-white;
  border-radius: 10px;
  z-index: 1;
}
.back {
  position: absolute;
  top: 16px;
  left: 16px;
  font-size: 14px;
}
h2 {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 14px;
}
.main-btn {
  width: 100%;
}
</style>
